//
//  NetworkTool.swift
//  sinaBlog
//
//  Created by tianxiangyang on 15/12/19.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

import AFNetworking

enum Method:String{
    case POST = "POST"
    case GET = "GET"
}

class NetworkTool: AFHTTPSessionManager {
    
    //创建一个单例
    static let sharedTool:NetworkTool = {
        
        //后端的url的host作为baseURL,这个在开发项目中,一般是不变的.
        let tool = NetworkTool(baseURL: NSURL(string: "https://api.weibo.com/"))
        
        tool.responseSerializer.acceptableContentTypes.insert("text/plain")
        
        
        return tool
        
        }()
    
    //封装网络请求的GET,POST方法.
    func requestDictToNetworkingWith(method:Method,urlString:String,parameters:[String:String],finished:(dict:[String:AnyObject]?,error:NSError?) ->()){
            //POST
        if method == Method.POST {
            
            NetworkTool.sharedTool.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                if let resultDict: AnyObject = result where (resultDict as? [String:AnyObject] != nil){
                    
                    //请求成功回调
                    finished(dict: resultDict as? [String : AnyObject], error: nil)
                    
                    return
                    
                }
                //请求失败
                //自定义错误对象
                /*api.weibo.com
                domain:baseURL的反转域名(com.weibo.api),code:状态码(一般与网络状态码区分,用负数填写),userInfo:附加提示信息(只能用这个key:NSLocalizedDescriptionKey).
                
                */
                let error = NSError(domain:"com.weibo.api", code: -100, userInfo: [NSLocalizedDescriptionKey:"数据不合法"])
                
                //失败的回调
                finished(dict: nil, error: error)
                
                
                }) { (_, error) -> Void in
                    //失败的回调
                    finished(dict: nil, error: error)
                    
                    print(error)
            }
        }
        //GET
        else{
        
        NetworkTool.sharedTool.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            if let resultDict: AnyObject = result where (resultDict as? [String:AnyObject] != nil){
                
                //请求成功回调
                finished(dict: resultDict as? [String : AnyObject], error: nil)
                
                return
                
            }

            let error = NSError(domain:"com.weibo.api", code: -100, userInfo: [NSLocalizedDescriptionKey:"数据不合法"])
            
            //失败的回调
            finished(dict: nil, error: error)
            
            
        }, failure: { (_, error) -> Void in
            
            //失败的回调
            finished(dict: nil, error: error)
            print(error)
        })
        
        
        
        }
    }
    


    
    
    
}
